package com.simtop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.dao.CountDao;
import com.simtop.pojo.IlabUser;
import com.simtop.pojo.User;
import com.simtop.pojo.YongdaoPo;
import com.simtop.service.JwtLoginService;
import com.simtop.service.UserService;
import com.simtop.util.*;
import com.simtop.vo.UserParamsVo;
import com.simtop.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户模块
 */
@Controller
@RequestMapping("/user")
@CrossOrigin //todo 跨域问题
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    @Autowired
    private UserService userService;

    @Autowired
    private JwtLoginService jwtLoginService;

    @Autowired
    private CountDao countDao;

    @Autowired
    private IlabUtil ilabUtil;

    @Autowired
    private ExcelUtils excelUtils;

    /**
     * 前台用户注册接口
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(@RequestBody UserVo userVo, HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("接收到的前台参数为："+userVo);
        return userService.register(userVo);
    }

    /**
     * 注册时 1、获取后台生成的邮箱验证码
     * 参数需要安全，接口安全
     * @return
     */
    @RequestMapping(value = "/checkCode",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> sendEmailCode(String email){
        //根据邮箱获取验证码
        return userService.generateCheckCode(email);
    }

    /**
     * ilab平台用户登陆 2019年10月11日15:50:32
     */
    @RequestMapping(value = "/ilab/login",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody IlabUser ilabUser, HttpServletRequest request){
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("获取到的ilab参数token为："+ilabUser.getToken());
        //获取ilab传递过来的token
        String token = ilabUser.getToken();
        try {
            /**
             * 调用ilab接口获取用户信息
             */
            String ilabJson = ilabUtil.getAccessToken(token);
            JSONObject o = JSONObject.parseObject(ilabJson);
            int code = o.getInteger("code");
            /**
             * 判断code不为0,则从ilab获取内容失败
             */
            if(code != 0){
                return ServerResponse.createByErrorMsg("token失效，请重新通过ilab进入重做实验");
            }
            String loginName = o.getString("un");
            String username  = o.getString("dis");
            //如果数据库存在登陆用户名 则直接返回
            User user =  userService.selectUserByLoginName(loginName);
            if(user != null){
                user.setAccessToken(URLEncoder.encode(o.getString("access_token"),"UTF-8"));
                System.out.println(URLEncoder.encode(o.getString("access_token"),"UTF-8"));
                String token1 = JwtUtil.sign(user,60L*1000L*60L*24);//token有效期10小时
                /**
                 * todo 统计网站访问次数：登陆成功后统计次数变量count加1
                 */
                int num = countDao.selectCount();
                int count = ++num;
                countDao.updateOne(count);
                return ServerResponse.createBySuccess(token1);
            }
            //不存在则在用户数据表中创建用户数据
            UserVo userVo = new UserVo();
            userVo.setLoginName(loginName);
            userVo.setUsername(username);
            userVo.setSchool("ilab平台用户");
            userVo.setProvince("ilab平台");
            userVo.setCity("ilab平台");
            //ilab用户身份
            userVo.setRoleId(5);
            userVo.setPassword(SHA256Util.generateShaPwd("12345"));
            userVo.setEmail("ilab@163.com");
            int resultCount = userService.insertIlabUser(userVo);
            //插入用户数据 给前端返回user的jwt对象
            User u =  userService.selectUserByLoginName(userVo.getLoginName());
            //将access_token放入用户对象生成token
            u.setAccessToken(URLEncoder.encode(o.getString("access_token"),"UTF-8"));
            System.out.println(URLEncoder.encode(o.getString("access_token"),"UTF-8"));
            //24小时的token有效期
            String token1 = JwtUtil.sign(u,60*60*1000*24L);
            int num = countDao.selectCount();
            int count = ++num;
            countDao.updateOne(count);
            return ServerResponse.createBySuccess(token1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMsg("新增ilab平台用户失败");
    }

    /**
     * 用户登录 成功后给前台返回一个token,后面需要拿这个token去验证
     * todo 用户类型：ilab用户 2019年9月24日15:34:07
     * 前台传入
     * @param userVo
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> login(@RequestBody UserVo userVo, HttpServletResponse response){
        // todo 如果是管理员或者评审专家 直接登陆 admin 123
        System.out.println("userVo"+userVo.getLoginName());
        System.out.println("userVoRoleId"+userVo.getRoleId());
        System.out.println("userVoPassword"+userVo.getPassword());

        if(userVo.getRoleId()==1||userVo.getRoleId()==3){
            User user = new User();
            //角色id
            user.setRoleId(userVo.getRoleId());
            //登录名
            user.setLoginName(userVo.getLoginName());
            //登陆密码
            user.setPassword(userVo.getPassword());
            return jwtLoginService.login(user);
        }
        User user = new User();
        //角色id
        user.setRoleId(userVo.getRoleId());
        //登录名
        user.setLoginName(userVo.getLoginName());
        //登陆密码
        user.setPassword(userVo.getPassword());
        return jwtLoginService.login(user);
    }

    /**
     * 忘记密码时获取验证码 邮箱验证码
     *
     */
    @RequestMapping(value = "/forget_checkCode",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<String> forgetSendEmailCode( String email){
        //根据邮箱获取验证码
        return userService.forgetSendEmailCode(email);
    }

    /**
     * 忘记密码时根据邮箱地址获取验证码 更新
     */
    @RequestMapping(value = "/updatePassword",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updatePassword(@RequestBody UserVo userVo){
        return userService.updatePassword(userVo);
    }

    /**
     * 用户管理 查看所有的数据
     */
    @RequestMapping(value = "/backend/findAll",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findAll(HttpServletRequest request, Integer pageNum, Integer pageSize,String school){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        if(ObjectUtils.isEmpty(pageNum)){
            pageNum = 1;
        }
        if(ObjectUtils.isEmpty(pageSize)){
            pageSize = 10;
        }
        PageHelper.startPage(pageNum,pageSize);
        User user = new User();
        user.setRoleId(u.getRoleId());
        user.setSchool(school);
        System.out.println(user);
        List<User> userList = userService.findAll(user);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }
    /**
     * 新增后台用户管理记录
     */
    @RequestMapping(value = "/backend/add",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> addUser(@RequestBody UserVo userVo, Integer userId, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.insertBackUser(userVo);
    }

    /**
     * 根据用户id删除User表数据
     */
    @RequestMapping(value = "/deleteByUserId",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> deleteById(@RequestBody String data, HttpServletRequest request){
        /**
         * 解析参数
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        Integer userId = jsonObject.getInteger("userId");
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        logger.info("管理员删除用户,编号为{}",userId);
        return userService.deleteByUserId(userId);
    }

    /**
     * 修改用户信息
     * @param userVo
     * @param
     * @param request
     * @return
     */
    @RequestMapping(value = "/backend/update",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> updateBackendUser(@RequestBody UserVo userVo, HttpServletRequest request){
        System.out.println("userId"+userVo);
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.updateBackendUser(userVo);
    }

    /**
     * 根据用户id查询用户信息
     */
    @RequestMapping(value = "/backend/findById",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<User> findUserById(HttpServletRequest request, Integer id){
        String token = request.getHeader("Authorization");
        if(token == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        return userService.findById(id);
    }

    /**
     * 用户查询功能(学校、姓名、登录名查询)
     */
    @RequestMapping(value = "/backend/findByParams",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo<User>> findByParams(HttpServletRequest request, UserParamsVo params, Integer pageNum, Integer pageSize){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        params.setRoleId(u.getRoleId());
        params.setUserId(u.getId());
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userService.findByParams(params);
        PageInfo<User> pageInfo = new PageInfo<User>(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    /**
     * 统计功能：统计用户总数量
     */
    @GetMapping("/userAccount")
    @ResponseBody
    public ServerResponse<Object> userAccount(HttpServletRequest request, HttpServletResponse response){
        try{
            return userService.getTopPageCount();
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("查询图表内容失败");
        }
    }

    /**
     * 获取模板
     */
    @GetMapping("/getUserTemplate")
    public void getUserTemplate(HttpServletRequest request,HttpServletResponse response){
        excelUtils.cooperation(request,response,User.class,"上传用户模板");
    }

    /**
     * 上传接口
     */
    @PostMapping("/importUser")
    @ResponseBody
    public ServerResponse<Object> importUsers(MultipartFile file){
        List<Object> upload = excelUtils.upload(file,User.class);
        return userService.importUsers(upload);
    }


    @PostMapping("/swfileOne")
    @ResponseBody
    public ServerResponse swfile(){


        try {

            String path = "cjj.xlsx";
            String as = "C:\\Users\\Administrator\\Desktop\\";

           // String as = "C:\\webProject\\Java\\yy\\";

            //String dir = "C:\\Users\\Administrator\\Desktop\\";
            List<YongdaoPo> YongDao = ReadExcelUtil.readExcel(as, path, "Sheet1");
            for (int i = 0; i < YongDao.size(); i++) {
                System.out.println(JSON.toJSONString(YongDao.get(i)));
            }
            ArrayList<Object> objects = new ArrayList<>();
            for (YongdaoPo os:YongDao
            ) {
                //    os.setPas(Integer.valueOf(password));
             //   os.setPassword( SHA256Util.generateShaPwd( os.getPassword().substring(0, os.getPassword().lastIndexOf("."))));
                os.setPassword(SHA256Util.generateShaPwd(os.getPassword()));
            }
            userService.insertYongdao(YongDao);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }



        return ServerResponse.createBySuccess();
    }
}